layui.define(["layer","form","jquery","table"],function (exports) {
    var table = layui.table,
        jquery = layui.jquery,
        form = layui.form,
        layer = layui.layer;
    var treetable = {
        // 渲染树形表格
        render: function (param) {
            // 检查参数
            if (!treetable.checkParam(param)) {
                return;
            }
            // 获取数据
            if (param.data) {
                treetable.init(param, param.data);
            } else {
                jquery.post(param.url, param.where, function (res) {
                    treetable.init(param, res);
                });
            }
        },
        // 渲染表格
        init: function (param, data) {
            var mData = [];
            var doneCallback = param.done;
            var tNodes = data;
            // 补上id和pid字段
            for (var i = 0; i < tNodes.length; i++) {
                var tt = tNodes[i];
                if (!tt.id) {
                    if (!param.treeIdName) {
                        layer.msg('参数treeIdName不能为空', {icon: 5});
                        return;
                    }
                    tt.id = tt[param.treeIdName];
                }
                if (!tt.pid) {
                    if (!param.treePidName) {
                        layer.msg('参数treePidName不能为空', {icon: 5});
                        return;
                    }
                    tt.pid = tt[param.treePidName];
                }
            }

            // 对数据进行排序
            var sort = function (s_pid, data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].pid == s_pid) {
                        var len = mData.length;
                        if (len > 0 && mData[len - 1].id == s_pid) {
                            mData[len - 1].isParent = true;
                        }
                        mData.push(data[i]);
                        sort(data[i].id, data);
                    }
                }
            };
            sort(param.treeSpid, tNodes);

            // 重写参数
            param.url = undefined;
            param.data = mData;
            param.page = {
                count: param.data.length,
                limit: param.data.length
            };

            param.cols[0][param.treeColIndex].templet = function (d) {
                var mId = d.id;
                var mPid = d.pid;
                var isDir = d.isParent;
                var emptyNum = treetable.getEmptyNum(mPid, mData);
                var iconHtml = '';
                for (var i = 0; i < emptyNum; i++) {
                    iconHtml += '<span class="treeTable-empty"></span>';
                }
                if (isDir) {
                    iconHtml += '<i class="layui-icon layui-icon-triangle-d"></i>';
                } else {
                }
                iconHtml += '&nbsp;&nbsp;';
                var ttype = isDir ? 'dir' : 'file';
                var vg = '<span class="treeTable-icon open" lay-tid="' + mId + '" lay-tpid="' + mPid + '" lay-ttype="' + ttype + '">';
                return vg + iconHtml + d[param.cols[0][param.treeColIndex].field] + '</span>'
            };
            param.done = function (res, curr, count) {
                jquery(param.elem).next().addClass('treeTable');
                jquery('.treeTable .layui-table-page').css('display', 'none');
                jquery(param.elem).next().attr('treeLinkage', param.treeLinkage);
                // 绑定事件换成对body绑定
                /*$('.treeTable .treeTable-icon').click(function () {
                    treetable.toggleRows($(this), param.treeLinkage);
                });*/
                if (param.treeDefaultClose) {
                    treetable.foldAll(param.elem);
                }
                if (doneCallback) {
                    doneCallback(res, curr, count);
                }
            };
            // 渲染表格
            table.render(param);
        },
        // 计算缩进的数量
        getEmptyNum: function (pid, data) {
            var num = 0;
            if (!pid) {
                return num;
            }
            var tPid;
            for (var i = 0; i < data.length; i++) {
                if (pid == data[i].id) {
                    num += 1;
                    tPid = data[i].pid;
                    break;
                }
            }
            return num + treetable.getEmptyNum(tPid, data);
        },
        // 展开/折叠行
        toggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-ttype');
            if ('file' == type) {
                return;
            }
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen) {
                $dom.removeClass('open');
            } else {
                $dom.addClass('open');
            }
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-tpid');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if (mId == pid) {
                    if (isOpen) {
                        jquery(this).hide();
                        if ('dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    } else {
                        jquery(this).show();
                        if (linkage && 'dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    }
                }
            });
        },
        // 检查参数
        checkParam: function (param) {
            if (!param.treeSpid && param.treeSpid != 0) {
                layer.msg('参数treeSpid不能为空', {icon: 5});
                return false;
            }

            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return false;
            }
            return true;
        }
        ,
        // 折叠所有
        foldAll: function (dom) {
            jquery(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = jquery(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && tOpen) {
                    $ti.trigger('click');
                }
            });
        }
    };

    layui.link('/css/treetable.css');

    // 给图标列绑定事件
    jquery('body').on('click', '.treeTable .treeTable-icon', function () {
        var treeLinkage = jquery(this).parents('.treeTable').attr('treeLinkage');
        if ('true' == treeLinkage) {
            treetable.toggleRows(jquery(this), true);
        } else {
            treetable.toggleRows(jquery(this), false);
        }
    });

    var object = {
        _option: {},
        // 初始化表格
        init : function (options) {
            //显示loading提示
            Layer.showLogin();
            this._option = options;
            table.render({
                id:options.id,
                elem: options.elem,
                method: options.method
                ,url: options.url
                ,data: options.data
                ,cols: options.cols
                ,limit: 20
                ,limits: [20,30,50,100]
                ,width : options.width
                ,height : options.height
                ,page: options.ispage
                ,where:{
                        orderBy:options.orderBy,
                        rule:options.rule
                }
                ,cellMinWidth: options.cellMinWidth
                ,done: function (res, curr, count) {
                    Layer.headLogin();
                    object.hoverOpenImg();
                },
                initSort:options.initSort
            });
        },

        // 初始化tree表格
        initTree:function (options) {
            //显示loading提示
            Layer.showLogin();
            this._option = options;
            treetable.render({
                treeColIndex: options.treeColIndex,          // 树形图标显示在第几列
                treeSpid: options.treeSpid,             // 最上级的父级id
                treeIdName: options.treeIdName,       // 	id字段的名称
                treePidName: options.treePidName,     // 	pid字段的名称
                treeDefaultClose: options.treeDefaultClose,   // 	是否默认折叠
                treeLinkage: options.treeLinkage,        // 	父级展开时是否自动展开所有子级
                elem: options.elem,
                url: options.url,
                cols: options.cols
                ,done: function (res, curr, count) {
                    Layer.headLogin();
                }
            });
        },
        //显示大图
        hoverOpenImg:function(){
            var img_show = null; // tips提示
            $('td img').hover(function(){
                var img = "<img class='img_msg' src='"+$(this).attr('src')+"' style='width:130px;' />";
                img_show = layer.tips(img, this,{
                    area: ['160px']
                });
            },function(){
                layer.close(img_show);
            });
            $('td img').attr('style','max-width:70px');
        },
        // 刷新表单
        reloads:function (value) {
            if('' == value){
                table.reload(this._option.id);
            }else{
                table.reload(this._option.id, {
                    where: value
                });
            }
        },
        // 搜索监听
        search:function () {
            form.on('submit(search)', function (data) {
                object.reloads(data.field);
                return false;
            });
        },
        // switch监听
        switch:function (value) {
            form.on('switch(*)', function (data) {
                var _this = $(this);
                $.achieve.post(value,{baseId:data.elem.id,isState:data.elem.checked?'Y':'N'},function (result) {
                    if(result.status == "success"){
                        Layer.showSucMsg(result.result);
                    }else{
                        Layer.showFailMsg(result.errorMsg);
                        _this.prop("checked",!_this.prop("checked"));
                        form.render("checkbox");
                    }
                })
            });
        },
        //工具按钮监听
        button:function () {

            $("body").on("click",".event_add",function () {
                Layer.openDialog($(this).val(),$(this).attr('href'));
            });

            $("body").on("click",".event_import",function () {
                Layer.openDialog($(this).val(),$(this).attr('href'));
            });

            $("body").on("click",".event_export",function () {
                $(this).attr('href',$(this).attr('href') + "?"+$("#from-search").serialize());
            });

            $("body").on("click",".event_delects",function () {
                var checkStatus = table.checkStatus(object._option.id),
                    data = checkStatus.data,
                    url = $(this).attr('href'),
                    ids = [];
                if(data.length > 0) {
                    for (var i in data) {
                        ids.push(data[i][object._option.onlyId]);
                    }
                    Layer.showConfirm("<p style='color: red'>确认删除吗？删除后不可恢复!</p>",function(){
                        post(url,{"ids":ids.toString()});
                    })
                }else{
                    Layer.showConfirm("请选择至少一条信息");
                }
            });
            table.on('tool(demo)', function(obj){
                var data = obj.data, //获得当前行数据
                    layEvent = obj.event; //获得 lay-event 对应的值
                var url = $(this).attr('href');
                if(layEvent == 'event_delect'){
                    //询问框
                    Layer.showConfirm("<p style='color: red'>确认删除吗？删除后不可恢复!</p>",function(){
                        post(url,{"baseId":data[object._option.onlyId]});
                    });
                }else{
                    Layer.openDialog($(this).val(),url+"?baseId="+data[object._option.onlyId]);
                }
            });
            function post(url,date) {
                $.achieve.post(url,date,function (result) {
                    if(result.status == "success"){
                        Layer.showSucMsg(result.result);
                        setTimeout("location.reload()",1000);
                    }else{
                        Layer.showFailMsg(result.errorMsg);
                    }
                });
            }
        },
        // 展开所有
        expandAll: function (dom) {
            jquery(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = jquery(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && !tOpen) {
                    $ti.trigger('click');
                }
            });
        }
    }

    exports("tabular",object);

})